package com.lsh.ofc.provider.rest.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.model.CommonResult;
import com.lsh.ofc.api.dto.OrderHeadShipDTO;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.core.entity.OfcObdHead;
import com.lsh.ofc.core.entity.OfcSoDetail;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.enums.SoStatus;
import com.lsh.ofc.core.enums.TaskModel;
import com.lsh.ofc.core.exception.EC;
import com.lsh.ofc.core.service.OfcObdService;
import com.lsh.ofc.core.service.OfcSoService;
import com.lsh.ofc.provider.rest.dto.ObdDetailDTO;
import com.lsh.ofc.provider.rest.dto.ObdHeadDTO;
import com.lsh.ofc.provider.rest.service.ObdRestService;
import com.lsh.ofc.provider.rest.service.OrderObdRestService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Project Name: lsh-ofc
 *
 * @author peter
 * @date 2019-09-17
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "rest", validation = "true")
@Path("order")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
@Slf4j
public class OrderObdRestServiceImpl implements OrderObdRestService {

    @Autowired
    private OfcSoService ofcSoService;

    @Autowired
    private OfcObdService ofcObdService;

    @Autowired
    private ObdRestService obdRestService;

    /**
     * 推送OBD
     *
     * @param orderHeadShipDTO
     * @return
     * @throws BusinessException
     */
    @POST
    @Path("/adapter/push")
    @Override
    public CommonResult<Boolean> orderPush(OrderHeadShipDTO orderHeadShipDTO) throws BusinessException {
        Long orderCode = orderHeadShipDTO.getOrderCode();
        log.info("adapter order push orderCode is {}", orderCode);

        try {
            OfcSoHead filter = new OfcSoHead();
            filter.setOrderCode(orderCode);
            List<OfcSoHead> soHeadList = this.ofcSoService.findList(filter, true);

            if (CollectionUtils.isEmpty(soHeadList)) {
                throw EC.ERROR.exception("obdHead 信息未找到 请稍后再试！");
            }

            OfcSoHead soHead = soHeadList.get(0);
            if (soHead.getSoStatus().compareTo(SoStatus.CREATED.getValue()) > 0) {
                return CommonResult.success(true);
            }

            Integer flag = orderHeadShipDTO.getReceiptFlag();
            if (null == flag) {
                flag = 0;
            }

            ObdHeadDTO obdHeadDTO = this.initObdHeadDTO(soHead, flag);

            return this.obdRestService.push(obdHeadDTO);
        } catch (BusinessException t) {
            log.error("adapter push obd info" + t.getCode() + ":" + t.getMessage(), t);
            return new CommonResult(t.getCode(), "业务处理错误:" + t.getMessage(), false);
        } catch (Exception t) {
            log.error("adapter push obd info", t);
            return new CommonResult(EC.SO_OBD_DEAL_ERROR.getCode(), "业务处理错误:数据处理异常或稍后再试", false);
        }
    }

    /**
     * 推送OBD
     *
     * @param obd
     * @return
     * @throws BusinessException
     */
    @POST
    @Path("/wumart/push")
    @Override
    public CommonResult<Boolean> wumartObdPush(OfcObdHead obd) throws BusinessException {

        try {
            log.info("wumart push obd info " + JSON.toJSONString(obd));
            OfcSoHead filter = new OfcSoHead();
            filter.setSoCode(obd.getSoCode());
            OfcSoHead soHead = ofcSoService.findOne(filter, false);

            if (null == soHead) {
                throw EC.ERROR.exception("so 信息不存在");
            }
            obd.setRegionCode(soHead.getRegionCode());
            obd.setSoBillCode(soHead.getSoBillCode());
            obd.setWarehouseCode(soHead.getWarehouseCode());
            obd.setFulfillChannel(soHead.getFulfillChannel());

            for (int i = 3; i > 0; i--) {
                try {
                    this.ofcObdService.create(obd, true, true);
                    break;
                } catch (Throwable t) {
                    if (i == 1) {
                        throw t;
                    }
                    continue;
                }
            }

            log.info("PUSH OBD end... success!!!");
        } catch (BusinessException t) {
            log.error("wumart push obd info" + t.getCode() + ":" + t.getMessage(), t);
            return new CommonResult(t.getCode(), "业务处理错误:" + t.getMessage(), false);
        } catch (Exception t) {
            log.error("wumart push obd info", t);
            return new CommonResult(EC.SO_OBD_DEAL_ERROR.getCode(), "业务处理错误:数据处理异常或稍后再试", false);
        }

        return CommonResult.success(true);
    }


    /**
     * @param soHead
     * @return
     */
    private ObdHeadDTO initObdHeadDTO(OfcSoHead soHead, Integer flag) {

        ObdHeadDTO obdHeadDTO = new ObdHeadDTO();
        obdHeadDTO.setMis(0);
        obdHeadDTO.setWms(soHead.getFulfillWms());
        obdHeadDTO.setWarehouseCode(soHead.getWarehouseCode());
        obdHeadDTO.setObdCode(soHead.getSoBillCode());
        obdHeadDTO.setSoCode(soHead.getSoBillCode());
        obdHeadDTO.setWaybillCode("0");
        obdHeadDTO.setCarrierCode("0");
        obdHeadDTO.setCarrierName("");
        obdHeadDTO.setBoxNum(1);
        obdHeadDTO.setTurnoverBoxNum(0);
        obdHeadDTO.setScatteredBoxNum(0);
        JSONObject misExt = new JSONObject();
        misExt.put(Constants.OBD_D_OBD_PACKAGE_NUM, "1");
        misExt.put(Constants.OBD_D_OBD_RECEIPT_FLAG, flag);
        obdHeadDTO.setMisExt(misExt.toJSONString());

        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        obdHeadDTO.setDeliveryTime(time + "");

        List<ObdDetailDTO> obdDetailDTOS = new ArrayList<>(soHead.getDetails().size());
        for (OfcSoDetail soDetail : soHead.getDetails()) {
            ObdDetailDTO obdDetailDTO = new ObdDetailDTO();

//            obdDetailDTO.setBarcode(misDetailDTO.getBarcode());
            obdDetailDTO.setSupplySkuCode(soDetail.getSkuSupplyCode());
            obdDetailDTO.setItemNo(soDetail.getItemCode() + "");
            obdDetailDTO.setSkuName(soDetail.getGoodsName());
            obdDetailDTO.setSkuQty(soDetail.getSkuOrderQty());
            obdDetailDTO.setGoodsCode(soDetail.getGoodsCode());
            obdDetailDTO.setBoxNum(1);
            if (soDetail != null && StringUtils.isBlank(obdDetailDTO.getSkuDefine())) {
                JSONObject extJson = JSON.parseObject(soDetail.getExt());
                obdDetailDTO.setSkuDefine(extJson.getString("sku_define"));
            }

            obdDetailDTO.setTaskModel(TaskModel.TASK_PART.getCode());
            obdDetailDTO.setPackNum(1);
            obdDetailDTO.setObdDetailExt("");
            JSONObject detailExt = new JSONObject();
            obdDetailDTO.setPreInfo(detailExt.toJSONString());
            obdDetailDTOS.add(obdDetailDTO);
        }
        obdHeadDTO.setDetails(obdDetailDTOS);

        return obdHeadDTO;
    }
}
